package com.lzx.iteam.adapter;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.*;
import android.widget.*;
import com.lzx.iteam.CloudDialerActivity;
import com.lzx.iteam.R;
import com.lzx.iteam.TreeFrag;
import com.lzx.iteam.bean.ChatContact;
import com.lzx.iteam.bean.ElementData;
import com.lzx.iteam.net.AsynHttpClient;
import com.lzx.iteam.net.GetMsgHttpReceiver;
import com.lzx.iteam.net.GroupContactMsg;
import com.lzx.iteam.net.LocalLogin;
import com.lzx.iteam.util.AllDialogUtil;
import com.lzx.iteam.util.Constants;
import com.umeng.analytics.MobclickAgent;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by hfx on 15-1-25.
 */
public class TreeViewAdapter extends BaseAdapter {


    public ElementData root;
    /**
     * 元素数据源
     */
    private ArrayList<ElementData> elementsData;
    /**
     * 树中元素
     */
    public ArrayList<ElementData> elements;
    /**
     * LayoutInflater
     */
    private LayoutInflater inflater;
    /**
     * item的行首缩进基数
     */
    private int indentionBase;
    TreeFrag treeflag;

    private static final int MSG_STRUCTURE_RENAME = 1000;
    private static final int MSG_STRUCTURE_ADD_NEXT_GROUP = 1001;
    private static final int MSG_STRUCTURE_DELETE_GROUP = 1002;
    private static final int MSG_STRUVTURE_GROUP_CONTACT = 1003;

    private Context mContext;
    private boolean isFirstItem;
    public String mName = "";
    public int mId = 0;
    public int selectId = 0;
    public int mParentId = 0;
    public int mGroupId = 0;
    public String mTagPath = "";
    public String mContactCount = "";
    public String mGroupName = "";
    int allCount = 0;
    String contactId = "";
    private CloudDialerActivity mActicvity;
    private AllDialogUtil dialogUtil;
    public int currentPosition;
    public boolean isGone;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_STRUCTURE_RENAME:
                    if (msg.arg1 == 0) {
                        Toast.makeText(mContext, "重命名成功", Toast.LENGTH_LONG).show();

                        SharedPreferences sp = mContext.getSharedPreferences("structure", Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putBoolean(String.valueOf(mGroupId) + "tag", false);
                        editor.commit();

                        Bundle bundle = msg.getData();
                        String name = bundle.getString("name");
                        ElementData element = (ElementData) getItem(currentPosition);
                        element.setContentText(name);

                        TreeViewAdapter.this.notifyDataSetChanged();

                        String tagId = ((ElementData) getItem(currentPosition)).getId() + "";
                        String tagName = ((ElementData) getItem(currentPosition)).getContentText();
                        String tagCount = ((ElementData) getItem(currentPosition)).getContactCount() + "";

                        Intent intent = new Intent();
                        intent.putExtra(Constants.INTENT_TAG_ID, tagId);
                        intent.putExtra(Constants.INTENT_TAG_NAME, tagName);
                        intent.putExtra("tag_count", tagCount);
                        intent.putExtra("group_id", String.valueOf(mGroupId));
                        intent.putExtra("group_name", mGroupName);
                        //intent.putIntegerArrayListExtra("clickPosition", clickPosition);
                        intent.putExtra("currentPosition", currentPosition);
                        //intent.putExtra("contact_count", Integer.valueOf(mContactCount));

                        intent.setAction("structure_tag_click");

                        CloudDialerActivity.instance.ListRefresh(intent, Activity.RESULT_OK,null);

                        //setTreeStyle(position);
                        //clickPosition.add(currentPosition);
                        selectId = ((ElementData) getItem(currentPosition)).getId();

                    } else {
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(mContext, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(mContext, (String) msg.obj,
                                    Toast.LENGTH_LONG).show();

                        }
                    }
                    break;
                case MSG_STRUCTURE_ADD_NEXT_GROUP:
                    if (msg.arg1 == 0) {
                        if (isFirstItem) {
                            Toast.makeText(mContext, "添加组成功", Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(mContext, "添加下一级组成功", Toast.LENGTH_LONG).show();
                        }

                        boolean isFirst = CloudDialerActivity.instance.mPreferenceUtil.getBoolean("structure_edit_v1", true);
                        if (isFirst) {
                            CloudDialerActivity.instance.mHelpStructureEdit.setVisibility(View.VISIBLE);
                        } else {
                            CloudDialerActivity.instance.mHelpStructureEdit.setVisibility(View.GONE);
                        }

                        SharedPreferences sp = mContext.getSharedPreferences("structure", Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putBoolean(String.valueOf(mGroupId) + "tag", false);
                        editor.commit();

                        JSONObject object = (JSONObject) msg.obj;

                        try {
                            JSONObject data = object.getJSONObject("data").getJSONObject("data");
                            int id = data.getInt("id");
                            int pid = data.getInt("pid");
                            String name = data.getString("name");
                            String path = data.getString("path");
                            long child_count = data.getLong("child_count");
                            long group_id = data.getLong("group_id");

                            int level = 1;
                            if (isFirstItem == false) {
                                ElementData parentelement = (ElementData) getItem(currentPosition);
                                parentelement.hasChildren = true;

                                if (parentelement.isExpanded == true) {
                                    setTreeStyle(currentPosition);
                                }
                                parentelement.hasChildren = true;
                                level = parentelement.level + 1;
                            } else {
                                pid = 0;
                            }

                            ElementData element = new ElementData(name, level, id, pid, child_count > 0 ? true : false, false);
                            elementsData.add(element);
                            treeflag.topElements.add(element);

                            if (isFirstItem == false) {
                                setTreeStyleAndFocus(currentPosition);
                            } else {
                                elements.add(element);

                                currentPosition = elements.size();//-1;
                                selectId = ((ElementData) getItem(currentPosition)).getId();

                                TreeViewAdapter.this.notifyDataSetChanged();
                            }


                            String tagId = ((ElementData) getItem(currentPosition)).getId() + "";
                            String tagName = ((ElementData) getItem(currentPosition)).getContentText();
                            String tagCount = ((ElementData) getItem(currentPosition)).getContactCount() + "";

                            Intent intent = new Intent();
                            intent.putExtra(Constants.INTENT_TAG_ID, tagId);
                            intent.putExtra(Constants.INTENT_TAG_NAME, tagName);
                            intent.putExtra("tag_count", tagCount);
                            intent.putExtra("group_id", String.valueOf(mGroupId));
                            intent.putExtra("group_name", mGroupName);
                            intent.putExtra("currentPosition", currentPosition);
                            //intent.putExtra("contact_count", Integer.valueOf(mContactCount));

                            intent.setAction("structure_tag_click");

                            CloudDialerActivity.instance.chooseelement = element;
                            CloudDialerActivity.instance.ListRefresh(intent, Activity.RESULT_OK, element);


                            //setTreeStyle(position);
                            selectId = ((ElementData) getItem(currentPosition)).getId();

                            // CloudDialerActivity.instance.recordintent = intent;


                        } catch (Exception e) {

                        }

                    } else {
//                        if (isFirstItem) {
//                            Toast.makeText(mContext, "添加组失败", 1).show();
//                        } else {
//                            Toast.makeText(mContext, "添加下一级组失败", 1).show();
//                        }
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(mContext, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(mContext, (String) msg.obj,
                                    Toast.LENGTH_LONG).show();

                        }
                    }
                    break;
                case MSG_STRUCTURE_DELETE_GROUP:
                    if (msg.arg1 == 0) {
                        Toast.makeText(mContext, "删除组成功", Toast.LENGTH_LONG).show();

                        SharedPreferences sp = mContext.getSharedPreferences("structure", Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putBoolean(String.valueOf(mGroupId) + "tag", false);
                        editor.commit();

                        ElementData element = (ElementData) getItem(currentPosition);
                        if (element.isExpanded == true) {
                            setTreeStyle(currentPosition);
                        }

                        //树中的元素
                        ArrayList<ElementData> elements = getElements();
                        //元素的数据源
                        ArrayList<ElementData> elementsData = getElementsData();

                        elements.remove(element);

                        for (ElementData t : elementsData) {
                            if (t.id == element.id) {
                                elementsData.remove(t);
                                for (ElementData s : treeflag.topElements) {
                                    if (s.id == t.id) {
                                        treeflag.topElements.remove(s);
                                        break;
                                    }
                                }
                                break;
                            }
                        }

                        selectId = -1;
                        currentPosition = -1;

                        for (int i = 1; i < elements.size() + 1; i++) {

                            ElementData item = (ElementData) getItem(i);
                            if (element.parendId == item.id) {
                                //item.isExpanded = false;
                                currentPosition = i;
                                selectId = item.getId();
                                break;
                            }
                        }

                        if (selectId == 0) {
                            selectId = -1;
                        }


                        treeflag.currentPosition = currentPosition;

                        if (currentPosition >= 0) {

                            setTreeStyle(currentPosition);

                            boolean find = false;
                            for (ElementData item : elementsData) {
                                if (item.parendId == selectId) {
                                    find = true;
                                    break;
                                }
                            }
                            if (find == false) {
                                ElementData findelement = (ElementData) getItem(currentPosition);
                                findelement.hasChildren = false;
                            }


                            TreeViewAdapter.this.notifyDataSetChanged();

                            String tagId = ((ElementData) getItem(currentPosition)).getId() + "";
                            String tagName = ((ElementData) getItem(currentPosition)).getContentText();
                            String tagCount = ((ElementData) getItem(currentPosition)).getContactCount() + "";

                            Intent intent = new Intent();
                            intent.putExtra(Constants.INTENT_TAG_ID, tagId);
                            intent.putExtra(Constants.INTENT_TAG_NAME, tagName);
                            intent.putExtra("tag_count", tagCount);
                            intent.putExtra("group_id", String.valueOf(mGroupId));
                            intent.putExtra("group_name", mGroupName);
                            intent.putExtra("currentPosition", currentPosition);
                            //intent.putExtra("contact_count", Integer.valueOf(mContactCount));

                            intent.setAction("structure_tag_click");

                            CloudDialerActivity.instance.ListRefresh(intent, Activity.RESULT_OK,null);

                            selectId = ((ElementData) getItem(currentPosition)).getId();


                        } else {
                            selectId = -1;
                            TreeViewAdapter.this.notifyDataSetChanged();

                            Intent intent = new Intent();
                            intent.putExtra(Constants.INTENT_TAG_ID, "0");
                            intent.putExtra(Constants.INTENT_TAG_NAME, "全部成员");
                            intent.putExtra("tag_count", "");
                            intent.putExtra("group_id", String.valueOf(mGroupId));
                            intent.putExtra("group_name", mGroupName);
                            intent.setAction("structure_tag_click");

                            CloudDialerActivity.instance.ListRefresh(intent, Activity.RESULT_OK,null);

                        }


                    } else {
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(mContext, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(mContext, (String) msg.obj,
                                    Toast.LENGTH_LONG).show();

                        }
                    }

                    break;
                case MSG_STRUVTURE_GROUP_CONTACT:
                    if (msg.arg1 == 0) {
                        ArrayList<ChatContact> list = (ArrayList<ChatContact>) msg.obj;
                        Intent intent = new Intent(mContext, CloudDialerActivity.class);
                        intent.setAction("set_structure_group_contact");
                        Bundle bundle = new Bundle();
                        bundle.putString("group_id", mGroupId + "");
                        bundle.putString(Constants.INTENT_TAG_NAME, mName);
                        bundle.putString("tag_id", mId + "");
                        bundle.putString("tag_path", mTagPath);
                        bundle.putString("tag_count", mContactCount);
                        bundle.putString("group_name", mGroupName);
                        bundle.putInt("currentPosition", currentPosition);
                        intent.putExtra("contact_count", allCount);
                        intent.putExtra("contact_id", contactId);
                        bundle.putParcelableArrayList("selectedContact", list);
                        intent.putExtras(bundle);
//                      mContext.startActivity(intent);
                        CloudDialerActivity.instance.initIntentData(intent);

                    } else {
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(mContext, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(mContext, (String) msg.obj,
                                    Toast.LENGTH_LONG).show();

                        }
                    }
                    break;
            }
        }
    };


    public TreeViewAdapter(LayoutInflater inflater, TreeFrag context, int groupId, String groupName, boolean isBatch, int allCount, String contactId) {
        this.inflater = inflater;
        indentionBase = 10;
        this.mContext = context.getActivity();
        this.treeflag = context;
        mActicvity = (CloudDialerActivity) mContext;
        dialogUtil = AllDialogUtil.getInstance((Activity) mContext);
        this.mGroupId = groupId;
        this.mGroupName = groupName;
        this.isGone = isBatch;
        this.allCount = allCount;
        this.contactId = contactId;

    }

    public void initData(ArrayList<ElementData> elements, ArrayList<ElementData> elementsData) {
        this.elements = elements;
        this.elementsData = elementsData;

    }

    public ArrayList<ElementData> getElements() {
        return elements;
    }

    public ArrayList<ElementData> getElementsData() {
        return elementsData;
    }

    @Override
    public int getCount() {
        return elements.size() + 1;
    }

    @Override
    public Object getItem(int position) {
        if (position == 0) {
            return root;
        }

        return elements.get(position - 1);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = inflater.inflate(R.layout.treeview_item, null);
            holder.disclosureLayout = (LinearLayout) convertView.findViewById(R.id.rl_disclosureImg);
            holder.disclosureImg = (ImageView) convertView.findViewById(R.id.disclosureImg);
            holder.contentText = (TextView) convertView.findViewById(R.id.contentText);
            holder.manageImg = (ImageView) convertView.findViewById(R.id.manage_treeview);
            holder.numberText = (TextView) convertView.findViewById(R.id.contactNumberText);
            holder.blankHolder = (ImageView) convertView.findViewById(R.id.blank_holder);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        if (position == 0) {
            //holder.disclosureLayout.setVisibility(View.GONE);
            holder.disclosureLayout.setPadding(
                    -45,
                    holder.disclosureLayout.getPaddingTop(),
                    holder.disclosureLayout.getPaddingRight(),
                    holder.disclosureLayout.getPaddingBottom());
            holder.contentText.setText(root.getContentText());
            holder.numberText.setText("(" + root.getContactCount() + ")");
            holder.disclosureImg.setImageResource(R.drawable.next);
            holder.disclosureImg.setVisibility(View.INVISIBLE);
            holder.blankHolder.setVisibility(View.GONE);

            if (treeflag.mCreateType.equals("3") || treeflag.mCreateType.equals("2") || treeflag.isBatch == true) {
                holder.manageImg.setVisibility(View.VISIBLE);
                holder.manageImg.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        // TODO Auto-generated method stub
                        if (treeflag.isBatch == false) {
                            TreeViewAdapter.this.showButtonWindow("全部成员", true, 0);
                        } else {
                            CloudDialerActivity.instance.changePage(true);
                        }
                    }
                });

                if (treeflag.isBatch == true) {
                    holder.manageImg.setImageResource(R.drawable.change_search);

                    holder.manageImg.setPadding(
                            0,
                            holder.manageImg.getPaddingTop(),
                            -10,
                            holder.manageImg.getPaddingBottom());

                } else {
                    holder.manageImg.setImageResource(R.drawable.selector_edit_more);
                }
            }

            if (this.selectId == -1) {
                convertView.setBackgroundResource(R.color.group_item_pressed);
            } else {
                convertView.setBackgroundResource(R.color.white);
            }

            return convertView;

        } else {
            position--;
            holder.manageImg.setVisibility(View.GONE);
        }


        final ElementData element = elements.get(position);
        int level = element.getLevel();
        if (level == 1) {

            holder.disclosureLayout.setPadding(
                    10,
                    holder.disclosureLayout.getPaddingTop(),
                    holder.disclosureLayout.getPaddingRight(),
                    holder.disclosureLayout.getPaddingBottom());
        } else {

            holder.disclosureLayout.setPadding(
                    indentionBase * (level + 1),
                    holder.disclosureLayout.getPaddingTop(),
                    holder.disclosureLayout.getPaddingRight(),
                    holder.disclosureLayout.getPaddingBottom());
            System.out.println("---level-" + level + "----left-" + indentionBase * (level + 2));
        }

        holder.contentText.setText(element.getContentText());
        holder.numberText.setText("(" + element.getContactCount() + ")");

        if (element.isHasChildren() && !element.isExpanded()) {
            holder.disclosureImg.setImageResource(R.drawable.next);
            //这里要主动设置一下icon可见，因为convertView有可能是重用了"设置了不可见"的view，下同。
            holder.disclosureImg.setVisibility(View.VISIBLE);
            holder.blankHolder.setVisibility(View.GONE);
        } else if (element.isHasChildren() && element.isExpanded()) {
            holder.disclosureImg.setImageResource(R.drawable.preview);
            holder.disclosureImg.setVisibility(View.VISIBLE);
            holder.blankHolder.setVisibility(View.GONE);
        } else if (!element.isHasChildren()) {
            holder.disclosureImg.setImageResource(R.drawable.next);
            holder.disclosureImg.setVisibility(View.INVISIBLE);
            holder.blankHolder.setVisibility(View.VISIBLE);
            //holder.contentText.setPadding(0, 15, 0, 15);
        }

        if (this.selectId == element.getId()) {
            convertView.setBackgroundResource(R.color.group_item_pressed);
        } else {
            convertView.setBackgroundResource(R.color.white);
        }

        return convertView;
    }

    /**
     * 优化Holder
     *
     * @author carrey
     */
    static class ViewHolder {
        LinearLayout disclosureLayout;
        ImageView disclosureImg;
        TextView contentText;
        TextView numberText;
        ImageView manageImg;
        ImageView blankHolder;
    }

    private PopupWindow mAddContactsWin;

    /**
     * 组织结构管理
     *
     * @param isFirst true表示是点击全部成员弹出的，false表示点击节点弹出的
     */
    public void showButtonWindow(String name, final boolean isFirst, int position) {

        if (mName == null || mName.length() == 0) {
            mName = name;
        }


        MobclickAgent.onEvent(mContext, "click_add_button");
        View mainView = ((Activity) mContext).getLayoutInflater().inflate(R.layout.alert_dialog_menu_structure_manage, null);
        TextView structure_name = (TextView) mainView.findViewById(R.id.structure_name);
        Button rename = (Button) mainView.findViewById(R.id.structure_rename);
        Button add_next_group = (Button) mainView.findViewById(R.id.structure_add_next_group);
        Button set_contact = (Button) mainView.findViewById(R.id.structure_set_contact);
        Button delete_group = (Button) mainView.findViewById(R.id.structure_delete_group);
        Button add_local_member = (Button) mainView.findViewById(R.id.structure_add_local_member);
        mAddContactsWin = new PopupWindow(mContext);
        mAddContactsWin.setBackgroundDrawable(new BitmapDrawable());
        mAddContactsWin.setFocusable(true);
        mAddContactsWin.setTouchable(true);
        mAddContactsWin.setOutsideTouchable(true); // 设置非PopupWindow区域可触摸
        mAddContactsWin.setContentView(mainView);
        mAddContactsWin.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
        mAddContactsWin.setHeight(WindowManager.LayoutParams.MATCH_PARENT);
        mAddContactsWin.setAnimationStyle(R.style.bottomStyle);
        structure_name.setText(mName);
        currentPosition = position;
        if (isFirst) {
            structure_name.setVisibility(View.GONE);
            //structure_name.setText("全部成员");
            add_next_group.setText("创建一级部门");
            rename.setVisibility(View.GONE);
            set_contact.setVisibility(View.GONE);
            delete_group.setVisibility(View.GONE);
            add_local_member.setVisibility(View.VISIBLE);
        }
        final String okText = mContext.getString(R.string.label_btn_ok);
        final String cancelText = mContext.getString(R.string.cancel);
        //重命名
        rename.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mAddContactsWin.dismiss();
                String addText = mContext.getString(R.string.edit_name);
                dialogUtil.titleEditBtnStyle(addText, mName, okText, cancelText, null);
                dialogUtil.setOnEditDialogListener(new AllDialogUtil.EditDialogOnClickListener() {

                    @Override
                    public void onConfirmClick(Dialog lDialog, EditText ed) {
                        String text = ed.getEditableText().toString().trim();
                        if (TextUtils.isEmpty(text)) {
                            Toast.makeText(mContext,
                                    R.string.structure_name_cannot_empty, Toast.LENGTH_LONG).show();
                            return;
                        } else {
                            rename(text);
                        }
                        lDialog.dismiss();
                        //mActicvity.showWait();
//                        showWait();
                    }

                    @Override
                    public void onCancelClick(Dialog lDialog, EditText ed) {
                        lDialog.dismiss();
                    }
                });
            }
        });
        //添加下一级组
        add_next_group.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mAddContactsWin.dismiss();
                String addText = "";
                if (isFirst) {
                    addText = "创建一级部门";
                } else {
                    addText = "添加下级部门";
                }
                dialogUtil.titleEditBtnStyle(mName, null, okText, cancelText, addText);
                dialogUtil.setOnEditDialogListener(new AllDialogUtil.EditDialogOnClickListener() {

                    @Override
                    public void onConfirmClick(Dialog lDialog, EditText ed) {
                        String text = ed.getEditableText().toString().trim();
                        if (TextUtils.isEmpty(text)) {
                            Toast.makeText(mContext,
                                    R.string.structure_name_cannot_empty, Toast.LENGTH_LONG).show();
                            return;
                        } else {
                            addNextGroup(text);
                            if (isFirst) {
                                isFirstItem = true;
                            } else {
                                isFirstItem = false;
                            }
                        }
                        lDialog.dismiss();
                        //mActicvity.showWait();
//                        showWait();
                    }

                    @Override
                    public void onCancelClick(Dialog lDialog, EditText ed) {
                        lDialog.dismiss();
                    }
                });
            }
        });
        //设置组成员
        set_contact.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mAddContactsWin.dismiss();
                getGroupContact(mHandler.obtainMessage(MSG_STRUVTURE_GROUP_CONTACT), mId + "");
                //mActicvity.showWait();
//                showWait();

            }
        });
        //删除组
        delete_group
                .setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        mAddContactsWin.dismiss();

                        dialogUtil.titleDeleteMsgStyle("删除" + mName + "组", okText, cancelText, "此操作会删除该部门及其子部门\n其中联系人不会被删除");
                        dialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {
                            @Override
                            public void onConfirmClick(Dialog lDialog) {
                                deleteGroup();
                                lDialog.dismiss();
                                //mActicvity.showWait();
//                                showWait();
                            }

                            @Override
                            public void onCancelClick(Dialog lDialog) {
                                lDialog.dismiss();

                            }

                        });
                    }
                });
        //从本地导入联系人
        add_local_member.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mAddContactsWin.dismiss();
                Intent intent = new Intent(mContext, CloudDialerActivity.class);
                intent.setAction("structure_add_local_member");
                intent.putExtra("group_id", mGroupId + "");
                intent.putExtra("contact_id", contactId);
                //intent.putExtra(Constants.INTENT_TAG_NAME, mName);
                //intent.putExtra("tag_id", "0");
                //intent.putExtra("tag_path", mTagPath);
                //intent.putExtra("tag_count", mContactCount);
                intent.putExtra("group_name", mGroupName);
                //intent.putExtra("contact_count", allCount);
                //mContext.startActivity(intent);
                CloudDialerActivity.instance.initIntentData(intent);
            }
        });
        //取消
        ((Button) mainView.findViewById(R.id.btn_cancel)).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mAddContactsWin.dismiss();
            }
        });
        mAddContactsWin.showAtLocation(mainView, Gravity.BOTTOM, 0, 0);
        mAddContactsWin.update();

        mainView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                mAddContactsWin.dismiss();
                return false;
            }
        });
    }

    public void rename(String newName) {
        //GetMsgHttpReceiver getMsg = new GetMsgHttpReceiver(mHandler.obtainMessage(MSG_STRUCTURE_RENAME));
        Message message = mHandler.obtainMessage(MSG_STRUCTURE_RENAME);
        Bundle bundle = new Bundle();
        bundle.putString("name", newName);
        message.setData(bundle);
        GetMsgHttpReceiver getMsg = new GetMsgHttpReceiver(message);

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        params.add(new BasicNameValuePair(AsynHttpClient.KEY_ID, mId + ""));
        params.add(new BasicNameValuePair(AsynHttpClient.KEY_NAME, newName));
        getMsg.mApi = AsynHttpClient.API_TAGS_UPDATE;
        getMsg.mParams = params;
        AsynHttpClient.getInstance(mContext).execCcHttp(getMsg);
    }

    private void addNextGroup(String groupName) {
        GetMsgHttpReceiver getMsg = new GetMsgHttpReceiver(mHandler.obtainMessage(MSG_STRUCTURE_ADD_NEXT_GROUP));
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        params.add(new BasicNameValuePair(AsynHttpClient.KEY_NAME, groupName));
        params.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, mGroupId + ""));
        params.add(new BasicNameValuePair(AsynHttpClient.KEY_FLAG, ""));
        params.add(new BasicNameValuePair(AsynHttpClient.KEY_ORDER_NUM, "1"));
        if (isFirstItem) {
            params.add(new BasicNameValuePair(AsynHttpClient.KEY_STRUCTURE_PID, "0"));
        } else {
            params.add(new BasicNameValuePair(AsynHttpClient.KEY_STRUCTURE_PID, mId + ""));
        }
        getMsg.mApi = AsynHttpClient.API_TAGS_ADD;
        getMsg.mParams = params;
        AsynHttpClient.getInstance(mContext).execCcHttp(getMsg);
    }

    private void deleteGroup() {
//      GetMsgHttpReceiver getMsg = new GetMsgHttpReceiver(mHandler.obtainMessage(MSG_STRUCTURE_DELETE_GROUP));
        Message message = mHandler.obtainMessage(MSG_STRUCTURE_DELETE_GROUP);
        Bundle bundle = new Bundle();
        bundle.putString("id", mId + "");
        message.setData(bundle);
        GetMsgHttpReceiver getMsg = new GetMsgHttpReceiver(message);

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        params.add(new BasicNameValuePair(AsynHttpClient.KEY_TAG_ID, mId + ""));
        getMsg.mApi = AsynHttpClient.API_TAGS_DELETE;
        getMsg.mParams = params;
        AsynHttpClient.getInstance(mContext).execCcHttp(getMsg);
    }


    public void setTreeStyle(int position) {
        {
            //点击的item代表的元素
            ElementData element = (ElementData) getItem(position);
            //树中的元素
            ArrayList<ElementData> elements = getElements();
            //元素的数据源
            ArrayList<ElementData> elementsData = getElementsData();

            //点击没有子项的item直接返回
            if (!element.isHasChildren()) {
                return;
                //http://192.168.18.170:8000/api/tags/contacts?group_id=11585&tag_id=69&sid=ACxXnEevVu45BX5eloqSGQ==
            }

            if (element.isExpanded()) {

                if (this.selectId == element.getId()) {
                    element.setExpanded(false);
                    //删除节点内部对应子节点数据，包括子节点的子节点...
                    ArrayList<ElementData> elementsToDel = new ArrayList<ElementData>();
                    for (int i = position /*+ 1*/; i < elements.size(); i++) {
                        if (element.getLevel() >= elements.get(i).getLevel())
                            break;
                        elementsToDel.add(elements.get(i));
                    }
                    elements.removeAll(elementsToDel);
                    notifyDataSetChanged();
                }


            } else {
                element.setExpanded(true);
                //从数据源中提取子节点数据添加进树，注意这里只是添加了下一级子节点，为了简化逻辑
                int i = 0;//1;//注意这里的计数器放在for外面才能保证计数有效
                for (ElementData e : elementsData) {
                    if (e.getParendId() == element.getId()) {
                        e.setExpanded(false);
                        elements.add(position + i, e);
                        i++;
                    }
                }
                notifyDataSetChanged();
            }
        }
    }


    public void setTreeStyleAndFocus(int position) {

        //点击的item代表的元素
        ElementData element = (ElementData) getItem(position);
        //树中的元素
        ArrayList<ElementData> elements = getElements();
        //元素的数据源
        ArrayList<ElementData> elementsData = getElementsData();


        element.setExpanded(true);
        //从数据源中提取子节点数据添加进树，注意这里只是添加了下一级子节点，为了简化逻辑
        int i = 0;//1;//注意这里的计数器放在for外面才能保证计数有效
        for (ElementData e : elementsData) {
            if (e.getParendId() == element.getId()) {
                e.setExpanded(false);
                elements.add(position + i, e);
                i++;
            }
        }

        currentPosition = currentPosition + i;//-1;
        selectId = ((ElementData) getItem(currentPosition)).getId();

        notifyDataSetChanged();


    }

    /**
     * 获取该节点下的成员
     */
    private void getGroupContact(Message callback, String tagId) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, mGroupId + ""));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_TAG_ID, tagId));
//      nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_IS_ALL, "1"));
        GroupContactMsg groupContactMsg = new GroupContactMsg(callback, mContext);
        groupContactMsg.mApi = AsynHttpClient.API_CONTACTS_BY_TAG;
        groupContactMsg.mParams = nvps;
        AsynHttpClient.getInstance(mContext).execCcHttp(groupContactMsg);
    }

}
